package at.fhj.itm09.snake.views;


import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * @author Susanne Brandstätter - Susanne.Brandstaetter.ITM09@fh-joanneum.at
 * @author Katharina Biela - Katharina.Biela.ITM09@fh-joanneum.at
 *
 * This class makes it possible to show a preview of the taken picture. 
 * It will be called, when a photo will be made. 
 * 
 * It extends SurfaceView to can show the picture.
 *  
 */

public class Preview extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder holder;
    public Camera camera;
    private Boolean previewRunning = false;
    
    public Preview(Context context) {
        super(context);
        
        /*
         * We need the SurfaceHolder.Callback, to get notified, when the
         * surface is created and destroyed.
         */
        holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    /**
     * This method is called, when the Surface has been created. 
     * It acquires the camera and tell it where the picture is to draw. 
     */
    public void surfaceCreated(SurfaceHolder holder) {
        //It opens the camera
        camera = Camera.open();
        try {
			camera.setPreviewDisplay(holder);
			camera.setPreviewCallback(new PreviewCallback() {

				@Override
				public void onPreviewFrame(byte[] data, Camera camera) { }
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    /**
     * The Surface will be destroyed, when you return to the settings menu, 
     * so when you stop the preview.
     */
    public void surfaceDestroyed(SurfaceHolder holder) {
    	if(camera != null){
    		camera.stopPreview();
    		previewRunning = false;
    		
    		camera.setPreviewCallback(null);
    		camera = null;
    	}
    }

    /**
     * Sets up the camera parameters and begin the preview.
     */
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

		if (previewRunning) {
			camera.stopPreview();
		}
		
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(w, h);
        parameters.set("orientation", "portrait");
        parameters.set("rotation", 90);
        
        camera.setParameters(parameters);
        camera.startPreview();
        
        previewRunning = true; 
    }

}